//
//  SSWBHomeViewController.swift
//  shanshanlol微博
//
//  Created by 叶竞泽 on 2017/1/7.
//  Copyright © 2017年 JingZe. All rights reserved.
//

import UIKit
import SKPhotoBrowser

/// 原创微博可重用cell
fileprivate let originalCellIdentifier = "originalCell"
/// 转发微博可重用cell
fileprivate let retweetCellIdentifier = "retweetCell"

class SSWBHomeViewController: SSWBBaseViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(showPhotoBrowser(notification:)), name: NSNotification.Name(rawValue: WBShowPhotoBrowserNotification), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 微博列表视图模型的懒加载
    fileprivate lazy var listViewModel = WBStatusListViewModel()
    
    /// 加载数据
    override func loadData() {
        
        refreshControl?.beginRefreshing()
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) {
            
            self.listViewModel.loadStatus(pullUp: self.isPullUp) { (isSuccess, hasMorePullUp) in
                
                // 刷新表格
                if hasMorePullUp {
                    self.tableView?.reloadData()
                    print("加载数据结束")
                }
                
                // 结束刷新控件
                self.refreshControl?.endRefreshing()
                
                // 恢复上拉刷新标记
                self.isPullUp = false
            }
        }
    }
    
    
    
    // MARK: - 监听方法
    
    /// 显示好友
    @objc fileprivate func showFriends() {
        
        let demoVC = SSWBDemoViewController()
        navigationController?.pushViewController(demoVC, animated: true)
    }
    
    /// 显示图片浏览器的通知监听方法
    ///
    /// - Parameter notification: 通知
    @objc fileprivate func showPhotoBrowser(notification: Notification) {
        
        guard let urls = notification.userInfo?[WBShowPhotoBrowserURLsKey] as? [String], let index = notification.userInfo?[WBShowPhotoBrowserSelectedIndexKey] as? Int else {
            return
        }
        
        // 1.create SKPhoto Array from UIImage
        var photos = [SKPhoto]()
        
        // 2.add some UIImage
        for url in urls {
            let photo = SKPhoto.photoWithImageURL(url)
            photo.shouldCachePhotoURLImage = false
            photos.append(photo)
        }
        
        // 3.create PhotoBrowser Instance, and present from your viewController.
        SKPhotoBrowserOptions.enableSingleTapDismiss = true
        let browser = SKPhotoBrowser(photos: photos)
        browser.initializePageIndex(index)
        
        // 4.show browser
        present(browser, animated: true) { 
            
        }
    }
}

// MARK: - 设置界面
extension SSWBHomeViewController {
    
    /// 重写父类方法
    override func setupUI() {
        
        super.setupUI()
        
        // 设置导航栏按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))
        // 注册原型cell
        tableView?.register(UINib(nibName: "SSWBStatusNormalCellTableViewCell", bundle: nil), forCellReuseIdentifier: originalCellIdentifier)
        tableView?.register(UINib(nibName: "SSWBStatusRetweetCellTableViewCell", bundle: nil), forCellReuseIdentifier: retweetCellIdentifier)
        // 设置行高
        // 取消自动行高
        tableView?.rowHeight = UITableViewAutomaticDimension
        tableView?.estimatedRowHeight = 300
        // 取消分割线
        tableView?.separatorStyle = .none
        // 设置导航栏标题
        setupNavTitle()
    }
    
    /// 设置导航栏标题
    fileprivate func setupNavTitle() {
        
        let button = SSWBTitleButton(title: SSWBNetworkManager.shared.userAccount.screen_name)
        button.addTarget(self, action: #selector(titleButtonClick(sender:)), for: .touchUpInside)
        navItem.titleView = button
    }
    
    @objc func titleButtonClick(sender: UIButton) {
        
        // 设置选中状态
        sender.isSelected = !sender.isSelected
        
    }
}

// MARK: - 数据源和代理
extension SSWBHomeViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return listViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 1.取出视图模型,根据视图模型判断可重用cell
        let model = listViewModel.statusList[indexPath.row]
        
        let cellId = model.status.retweeted_status != nil ? retweetCellIdentifier : originalCellIdentifier
        // 2.取出cell - 本身会调用代理方法(如果有) / 如果没有,找到cell,按照自动布局的规则,从上向下计算,找到向下的约束,从而计算动态行高
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! SSWBStatusCellTableViewCell
        // 3.设置cell
        cell.viewModel = model
        // 4.设置cell的代理
        cell.delegate = self
        
        return cell
    }
    
    // 手动计算行高
//    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        
//        // 1.根据index获取视图模型
//        let model = listViewModel.statusList[indexPath.row]
//        return model.rowHeight
//    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
}

extension SSWBHomeViewController: SSWBStatusCellTableViewCellDelegate {
    
    func statusCellTableViewCellDidTapURLString(cell: SSWBStatusCellTableViewCell, urlString: String) {
        
        let webViewController = SSWBWebViewController()
        webViewController.urlString = urlString
        navigationController?.pushViewController(webViewController, animated: true)
    }
}
